package com.opal.salescost.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.opal.salescost.source.SalescostThreadLocalDS;
import com.opal.system.entity.BdCustomerForm;
import com.opal.salescost.entity.SalesorgForm;
import com.opal.system.entity.table.BdCustomer;
import com.opal.system.entity.table.OpalUser;
import com.opal.salescost.entity.table.VCxSalescostZp;
import com.opal.salescost.entity.table.VcXsalescostOp;
import com.opal.system.service.HRService;
import com.opal.salescost.service.SalescostOpService;
import com.opal.salescost.service.SalescostZpService;
import com.opal.system.service.StoredProcedureService;
import com.opal.utils.ExcelDownloadUtil;
import com.opal.utils.PageVOUtils;
import com.opal.vo.PageVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 销售成本明细表
 */
@Controller
@Slf4j
@RequestMapping("/salesorg")
public class SalesorgController {

    @Autowired
    private HRService orgSalesorgService;

    @Autowired
    private SalescostOpService salescostOpService;

    @Autowired
    private SalescostZpService salescostZpService;



    /**
     * 查询客户名称
     * @param from
     * @param page
     * @param rows
     * @return
     */
    @RequestMapping("/bdCustomer")
    @ResponseBody
    public PageVO<BdCustomer> bdCustomerList(BdCustomerForm from, @RequestParam("page") int page, @RequestParam("rows") int rows) {

        int Total = orgSalesorgService.findTotal(from);
        //分页查询
        List<BdCustomer> nameList = orgSalesorgService.findByNamePage(from,page,rows);
        return PageVOUtils.success(Total, nameList);
    }

    /**
     * 查询数据
     *
     * @param form
     * @param page
     * @param rows
     * @return
     */
    @RequestMapping("/check")
    @ResponseBody
    public PageVO<T> check(@Valid SalesorgForm form,
                           @RequestParam("page") int page, @RequestParam("rows") int rows) {
        if (!StringUtils.isBlank(form.getDsName())){
            new SalescostThreadLocalDS("two");
        }else {
            new SalescostThreadLocalDS("");
        }
        //获取用户名字
        Subject subject = SecurityUtils.getSubject();
        OpalUser user=(OpalUser) subject.getPrincipal();
//        form.setWLCode(form.getWLCode().replaceAll(",", "|"));
        form.setFirstIndex((page - 1) * rows);
        form.setLastIndex(page * rows);
        if (form.getPkSalesorg() == null) {
            return null;
        }
        //如果勾选重新计算将执行  否则直接显示结果
        if (form.getCheckbox().equals("true")) {
            log.info("用户: "+user.getUserName()+" 执行了销售订单明细表(重新计算)存储过程！");
            return salescostZpService.getPage(form);
        }
        int Total = salescostOpService.getCount(form);
        List<VcXsalescostOp> vcXsalescostOpList = salescostOpService.getPage(form);
        return PageVOUtils.success(Total, vcXsalescostOpList);
    }


    /**
     * 导出EXCEL
     *
     * @param form
     * @param response
     * @throws Exception
     */
    @RequestMapping("/excel_down")
    public void excel_down(SalesorgForm form, HttpServletResponse response, HttpServletRequest request) throws Exception {
        if (!StringUtils.isBlank(form.getDsName())){
            new SalescostThreadLocalDS("two");
        }else {
            new SalescostThreadLocalDS("");
        }
        //获取用户名字
        Subject subject = SecurityUtils.getSubject();
        OpalUser user=(OpalUser) subject.getPrincipal();
        //当前时间
        Date date = new Date();
        String time = new SimpleDateFormat("yyyy-MM-dd").format(date);
//        form.setWLCode(form.getWLCode().replaceAll(",", "|"));

        //如果勾选重新计算将执行  否则直接导出
        if (form.getCheckbox() != null && form.getCheckbox() != "") {
//          执行存储过程 再执行导出
            String Time = form.getStartTime().substring(0, 7);
            salescostZpService.CallGpCxSaleccost(Time,form.getPkSalesorg());
            List<VCxSalescostZp> vCxSalescostZpList = salescostZpService.findAll(form);
            Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("销售订单明细表(重新计算) " + time, time), VCxSalescostZp.class, vCxSalescostZpList);
            ExcelDownloadUtil.ExcelUtil(response, workbook, "销售订单明细表(重新计算) " + time + ".xls",request);
            log.info("用户: "+user.getUserName()+" 执行了销售订单明细表(重新计算)存储过程并导出！");
        }
//      否则直接查询导出
        List<VcXsalescostOp> vcXsalescostOpList = salescostOpService.findAll(form);
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("销售订单明细表 " + time, time), VcXsalescostOp.class, vcXsalescostOpList);
        ExcelDownloadUtil.ExcelUtil(response, workbook, "销售订单明细表 " + time + ".xls",request);
    }



    /**
     * 获取导出结束返回值
     *
     * @param request
     * @throws Exception
     */
    @RequestMapping("/getendflag")
    @ResponseBody
    public Map getendflag(HttpServletRequest request){
        HttpSession session = request.getSession();
        Object flag = session.getAttribute("endflag"); //获取结束标记*/
        session.removeAttribute("endflag");
        Map obj = new HashMap();
        obj.put("flag", flag);//返回状态值
        return obj;
    }



    // @RequiresPermissions(value={"aaa"})
    @RequestMapping("{page}")
    public String skipPage(@PathVariable("page") String page) {
        return "salesorg/" + page;
    }

}